import { ref, onMounted, onUnmounted } from 'vue'
import { ctpService } from '../services/ctpService'
import { Modal } from 'ant-design-vue'
import { invoke } from '@tauri-apps/api/core'
import { useDailyPositionTracker } from './useDailyPositionTracker.js'
import { usePositionData } from './usePositionData.js'
import { useContractStore } from '../stores/contractStore'
import { useOrderValidation } from './useOrderValidation.js'

export function useTrading(contractCode = 'global', windowIdRef = null) {
  // 窗口ID引用，支持动态更新
  const windowId = windowIdRef || ref('')

  // 初始化每日持仓跟踪器 - 按合约隔离
  const {
    cPosition,
    tPosition,
    incrementCancelCount,
    incrementTradeCount,
    getTradingDayInfo
  } = useDailyPositionTracker(contractCode)

  // 获取持仓数据管理器
  const {
    handleTradeNotification: handlePositionTradeNotification
  } = usePositionData()

  // 获取合约存储
  const { getCurrentContract } = useContractStore()

  // 初始化订单验证
  const { validateOrder, isValidating } = useOrderValidation()

  // 交易相关状态
  const selectedCell = ref(null)
  const lightOrderQuantity = ref(1)
  const heavyOrderQuantity = ref(2)
  const orderPrice = ref(2)
  const orderType = ref('A')

  // 交易选项配置
  const options = ref({
    autoHand: false,
    cLimit499: true,  // 默认选中499撤单限制
    noLimit: false,
    noCombo: true,
    upLimit: false
  })

  // 订单状态管理
  const hasActiveOrder = ref(false)
  const lastOrderRef = ref('')
  const orderStatus = ref('')
  const orderDetails = ref(null)
  const activeOrders = ref([])
  const cancelResults = ref(new Map())

  // 判断是否选中
  const isSelected = (type, field, index) => {
    return selectedCell.value?.type === type &&
      selectedCell.value?.field === field &&
      selectedCell.value?.index === index
  }

  // 处理下单点击
  const handleOrderClick = (orderType, data, index, event, section) => {
    const isRightClick = event?.button === 2
    const orderQuantity = isRightClick ? heavyOrderQuantity.value : lightOrderQuantity.value
    const orderMode = isRightClick ? '重仓' : '轻仓'

    const currentSection = section || (data.color === 'red' ? 'sell' : 'buy')

    // 实施交易限制规则
    if (currentSection === 'sell') {
      if (orderType === 'buy') {
        return
      }
    } else if (currentSection === 'buy') {
      if (orderType === 'sell') {
        return
      }
    }

    selectedCell.value = {
      type: orderType,
      field: orderType,
      value: data.price,
      data,
      index,
      quantity: orderQuantity
    }

    orderPrice.value = data.price
    placeOrder()
  }

  // 下单操作
  const placeOrder = async () => {
    if (!selectedCell.value) return

    const { type, quantity } = selectedCell.value
    const orderQuantity = quantity || lightOrderQuantity.value

    try {
      // 检查结算确认状态
      const settlementResult = await ctpService.checkSettlementConfirmStatus()
      if (!settlementResult.success || !settlementResult.data) {
        const confirmResult = await ctpService.settlementInfoConfirm()
        if (!confirmResult.success) {
          return
        }
      }
      // 获取当前合约代码
      const currentContract = getCurrentContract()
      const contractCode = currentContract?.code

      if (!contractCode) {
        return { success: false, error: '请先选择合约' }
      }
      // 构建订单请求
      const orderRequest = {
        instrument_id: contractCode,
        direction: type === 'buy' ? '0' : '1',
        price: orderPrice.value,
        volume: orderQuantity,
        order_type: '2',        // 限价单
        offset_flag: '0',       // 开仓
        hedge_flag: '1',        // 投机
        time_condition: '1',    // GTC - 撤销前有效（而不是IOC立即完成否则撤销）
        volume_condition: '1'   // 任何数量
      }

      // 创建窗口上下文
      const windowContext = {
        windowId: windowId.value,
        contractCode: contractCode
      }

      // 🔍 验证订单
      console.log('🔍 [TRADING] 开始验证订单...')
      const validationResult = await validateOrder(orderRequest, windowContext)
      
      if (!validationResult.isValid) {
        console.error('❌ [TRADING] 订单验证失败，取消下单')
        // 验证失败时已经显示了错误消息和播放了提示音
        clearSelection()
        return { success: false, error: '订单验证失败' }
      }
      
      console.log('✅ [TRADING] 订单验证通过，提交订单...')

      const result = await ctpService.insertOrder(orderRequest, windowContext)

      if (result.success) {
        const orderMode = quantity === heavyOrderQuantity.value ? '重仓' : '轻仓'
        // 从返回消息中提取真实的订单引用号
        let realOrderRef = null

        // 尝试多种可能的格式
        const patterns = [
          /订单引用:\s*(\d+)/,
          /order_ref:\s*(\d+)/i,
          /OrderRef:\s*(\d+)/,
          /ref:\s*(\d+)/i,
          /引用:\s*(\d+)/,
          /"order_ref":\s*"?(\d+)"?/,
          /order_ref=(\d+)/i
        ]

        for (const pattern of patterns) {
          const match = String(result.data).match(pattern)
          if (match) {
            realOrderRef = match[1]
            break
          }
        }

        // 如果还是没有找到，尝试从日志中获取最新的订单引用号
        if (!realOrderRef) {
          realOrderRef = 'pending_' + Date.now()
        }

        if (realOrderRef) {
          // 添加到活跃订单列表
          addActiveOrder(realOrderRef, {
            ...orderRequest,
            orderRef: realOrderRef,
            instrumentId: orderRequest.instrument_id,
            direction: type === 'buy' ? '买入' : '卖出',
            submitTime: new Date().toLocaleTimeString()
          })

          // 更新订单状态
          lastOrderRef.value = realOrderRef
          hasActiveOrder.value = true
          orderStatus.value = 'submitted'
          orderDetails.value = {
            orderRef: realOrderRef,
            price: orderPrice.value,
            volume: orderQuantity,
            direction: type,
            submitTime: new Date().toLocaleTimeString(),
            status: 'submitted'
          }
        }

        clearSelection()
      }

    } catch (error) {
    }
  }

  // 撤单操作
  const cancelOrder = async () => {
    if (!lastOrderRef.value) {
      return { success: false, error: '没有可撤销的订单' }
    }

    try {
      // 获取当前合约代码
      const currentContract = getCurrentContract()
      const contractCode = currentContract?.code
      // 创建窗口上下文
      const windowContext = {
        windowId: windowId.value,
        contractCode: contractCode
      }

      const result = await ctpService.cancelOrder(lastOrderRef.value, contractCode, windowContext)

      if (result.success) {
        // 增加撤单计数 - 传递合约代码
        incrementCancelCount(contractCode)

        // 从活跃订单列表中移除
        removeActiveOrder(lastOrderRef.value)

        // 更新状态
        hasActiveOrder.value = activeOrders.value.length > 0
        if (activeOrders.value.length === 0) {
          lastOrderRef.value = ''
          orderStatus.value = ''
        }

        clearSelection()
        return { success: true, data: result.data }
      } else {
        return { success: false, error: result.error }
      }

    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 清除选择
  const clearSelection = () => {
    selectedCell.value = null
  }

  // 监听订单更新事件
  const handleOrderUpdate = (orderUpdate) => {
    // 如果是新订单且状态为未知(97)或未成交还在队列中(51)
    if (orderUpdate.order_ref && (orderUpdate.order_status === 97 || orderUpdate.order_status === 51)) {
      const orderRef = String(orderUpdate.order_ref)

      // 检查是否是我们刚刚下的订单（通过时间戳判断）
      const now = Date.now()
      const recentOrders = activeOrders.value.filter(order =>
        order.orderRef.startsWith('pending_') &&
        (now - parseInt(order.orderRef.split('_')[1])) < 10000 // 10秒内的订单
      )

      if (recentOrders.length > 0) {
        const pendingOrder = recentOrders[0]

        // 更新订单引用号
        pendingOrder.orderRef = orderRef
        lastOrderRef.value = orderRef

        // 更新订单详情
        if (orderDetails.value && orderDetails.value.orderRef === pendingOrder.orderRef) {
          orderDetails.value.orderRef = orderRef
        }
      }
    }

    // 如果订单被撤销(53)或全部成交(48)，从活跃订单列表中移除
    if (orderUpdate.order_ref && (orderUpdate.order_status === 53 || orderUpdate.order_status === 48)) {
      const orderRef = String(orderUpdate.order_ref)
      removeActiveOrder(orderRef)
    }
  }

  // 处理成交通知事件
  const handleTradeNotification = (tradeData) => {

    // 只处理当前合约的成交通知
    const tradeContractCode = tradeData.instrument_id
    if (tradeContractCode === contractCode) {
      // 增加成交计数
      incrementTradeCount(tradeContractCode)

      // 将成交通知传递给持仓数据管理器进行持仓更新
      // 这里需要判断是否为平仓单，暂时设为false（开仓）
      const isClosing = false // TODO: 根据实际业务逻辑判断是否为平仓
      handlePositionTradeNotification(tradeData, isClosing)
    }
  }

  // 初始化订单更新监听
  onMounted(() => {
    ctpService.on('order_update', handleOrderUpdate)
    ctpService.on('trade_notification', handleTradeNotification)
  })

  onUnmounted(() => {
    ctpService.off('order_update', handleOrderUpdate)
    ctpService.off('trade_notification', handleTradeNotification)
  })

  // 活跃订单管理
  const addActiveOrder = (orderRef, orderInfo) => {
    const order = {
      orderRef,
      instrumentId: orderInfo.instrument_id,
      direction: orderInfo.direction === '0' ? 'buy' : 'sell',
      price: orderInfo.price,
      volume: orderInfo.volume,
      submitTime: new Date().toLocaleTimeString(),
      ...orderInfo
    }

    activeOrders.value.push(order)
    hasActiveOrder.value = true
    lastOrderRef.value = orderRef
  }

  const removeActiveOrder = (orderRef) => {
    const index = activeOrders.value.findIndex(order => order.orderRef === orderRef)

    hasActiveOrder.value = activeOrders.value.length > 0
    if (activeOrders.value.length === 0) {
      lastOrderRef.value = ''
    }
  }

  const clearActiveOrders = () => {
    activeOrders.value = []
    hasActiveOrder.value = false
    lastOrderRef.value = ''
  }

  // 撤销所有挂单功能
  const cancelAllOrders = async () => {
    try {
      if (activeOrders.value.length === 0) {
        return { success: false, message: '没有可撤销的挂单' }
      }
      const ordersToCancel = [...activeOrders.value]
      let successCount = 0
      let failCount = 0
      const results = []

      // 逐个撤销订单
      for (const order of ordersToCancel) {
        try {
          // 获取当前合约代码
          const currentContract = getCurrentContract()
          const contractCode = currentContract?.code

          if (!contractCode) {
            return { success: false, error: '请先选择合约' }
          }

          // 构造完整的撤单请求
          const cancelRequest = {
            instrument_id: order.instrumentId || contractCode,
            order_ref: order.orderRef,
            front_id: null,
            session_id: null,
            exchange_id: "SHFE",
            order_sys_id: null
          }

          // 创建窗口上下文
          const windowContext = {
            windowId: windowId.value,
            contractCode: order.instrumentId || contractCode
          }

          const result = await ctpService.cancelOrderWithRequest(cancelRequest, windowContext)

          if (result.success) {
            successCount++
            results.push(`✅ 订单${order.orderRef}: 撤单请求已提交`)
            // 增加撤单计数 - 传递合约代码
            incrementCancelCount(order.instrumentId || contractCode)
            removeActiveOrder(order.orderRef)
          } else {
            failCount++
            const errorMsg = result.error || '未知错误'

            if (errorMsg.includes('已全成交') || errorMsg.includes('已撤销') || errorMsg.includes('不能再撤')) {
              results.push(`ℹ️ 订单${order.orderRef}: 订单已成交，无需撤单`)
            } else {
              results.push(`❌ 订单${order.orderRef}: ${errorMsg}`)
            }

            removeActiveOrder(order.orderRef)
          }

          // 添加短暂延迟，避免请求过快
          await new Promise(resolve => setTimeout(resolve, 50))

        } catch (error) {
          failCount++
          results.push(`❌ 订单${order.orderRef}: 撤单异常`)
        }
      }

      // 清空最后一个订单引用
      if (lastOrderRef.value) {
        lastOrderRef.value = null
        orderStatus.value = ''
      }

      const summary = `撤单完成！请求提交: ${successCount}个，直接失败: ${failCount}个，剩余挂单: ${activeOrders.value.length}个`

      return {
        success: true,
        message: summary,
        details: {
          successCount,
          failCount,
          remainingOrders: activeOrders.value.length,
          results
        }
      }

    } catch (error) {
      return { success: false, message: '撤销所有挂单过程中发生错误', error }
    }
  }

  // 全撤操作锁 - 防止并发冲突
  const isCancellingAll = ref(false)

  // 撤销账号下所有挂单功能
  const cancelAllAccountOrders = async () => {
    // 检查是否正在执行全撤操作
    if (isCancellingAll.value) {
      return {
        success: false,
        message: '正在执行全撤操作，请稍候',
        isLocked: true
      }
    }

    try {
      // 加锁
      isCancellingAll.value = true

      // 查询账号下所有未成交订单
      const queryResult = await ctpService.queryAllOrders()

      if (queryResult.success) {
        const allOrders = queryResult.data || []

        if (allOrders.length === 0) {
          return { success: true, message: '账号下没有未成交的订单' }
        }

        // 统计每个合约的唯一价格档位数（用于撤单计数）
        // 使用 Map<合约代码, Set<价格>> 来去重价格
        const contractPricesMap = new Map()

        let successCount = 0
        let failCount = 0
        const results = []

        // 逐个撤销订单
        for (const order of allOrders) {
          try {
            // 构造完整的撤单请求
            const cancelRequest = {
              instrument_id: order.instrument_id,
              order_ref: order.order_ref,
              front_id: order.front_id || null,
              session_id: order.session_id || null,
              exchange_id: "SHFE", // 根据合约确定交易所
              order_sys_id: order.order_sys_id || null
            }

            // 创建窗口上下文 - 账号全撤时不指定特定窗口，让后端决定通知策略
            const windowContext = {
              windowId: '', // 空字符串表示账号全撤操作
              contractCode: order.instrument_id
            }

            const result = await ctpService.cancelOrderWithRequest(cancelRequest, windowContext)

            if (result.success) {
              successCount++
              results.push(`✅ ${order.instrument_id} 订单${order.order_ref}: 撤单请求已提交`)

              // 记录该合约的价格（用于统计唯一价格档位数）
              const contractCode = order.instrument_id
              if (!contractPricesMap.has(contractCode)) {
                contractPricesMap.set(contractCode, new Set())
              }
              contractPricesMap.get(contractCode).add(order.price)

            } else {
              failCount++
              const errorMsg = result.error || '未知错误'
              results.push(`❌ ${order.instrument_id} 订单${order.order_ref}: ${errorMsg}`)
            }

            // 添加短暂延迟
            await new Promise(resolve => setTimeout(resolve, 50))

          } catch (error) {
            failCount++
            results.push(`❌ ${order.instrument_id} 订单${order.order_ref}: 撤单异常`)
          }
        }

        const contractCancelCounts = new Map()
        for (const [contractCode, pricesSet] of contractPricesMap.entries()) {
          const uniquePriceCount = pricesSet.size
          contractCancelCounts.set(contractCode, uniquePriceCount)
        }
        // 通知所有相关的交易面板更新撤单量
        await notifyTradingPanelsForCancelCounts(contractCancelCounts)

        const summary = `账号全撤完成！请求提交: ${successCount}个，直接失败: ${failCount}个`

        return {
          success: true,
          message: summary,
          details: {
            totalOrders: allOrders.length,
            successCount,
            failCount,
            results
          }
        }

      } else {
        return { success: false, message: `查询订单失败: ${queryResult.error}` }
      }

    } catch (error) {
      return { success: false, message: '账号全撤过程中发生错误', error }
    } finally {
      // 解锁
      isCancellingAll.value = false
    }
  }

  // 通知所有交易面板更新撤单量
  const notifyTradingPanelsForCancelCounts = async (contractCancelCounts) => {
    try {
      // 获取所有窗口
      const { getAllWindows } = await import('@tauri-apps/api/window')
      const allWindows = await getAllWindows()
      // 确保 allWindows 是数组
      let windowsArray = []
      if (Array.isArray(allWindows)) {
        windowsArray = allWindows
      } else if (allWindows && typeof allWindows === 'object') {
        windowsArray = Object.values(allWindows)
      } else {
        return
      }

      // 向每个交易面板窗口发送撤单计数更新事件
      for (const window of windowsArray) {
        try {
          if (!window || !window.label) {
            continue
          }
          const label = window.label
          // 只处理交易面板窗口
          if (label.includes('trading-panel')) {
            const payload = {
              contractCancelCounts: Object.fromEntries(contractCancelCounts),
              timestamp: Date.now()
            }

            // 向窗口发送窗口特定的事件（使用窗口label作为事件名的一部分）
            const windowSpecificEvent = `account-cancel-orders-${label}`
            await window.emit(windowSpecificEvent, payload)
          }
        } catch (error) {
        }
      }

    } catch (error) {
    }
  }

  // 获取总量显示
  const getTotalVolume = (item) => {
    const buyVol = item.buyVolume || 0
    const sellVol = item.sellVolume || 0
    const total = buyVol + sellVol
    return total > 0 ? total.toString() : ''
  }



  return {
    // 状态
    selectedCell,
    lightOrderQuantity,
    heavyOrderQuantity,
    orderPrice,
    orderType,
    options,
    hasActiveOrder,
    lastOrderRef,
    orderStatus,
    orderDetails,
    activeOrders,
    cancelResults,
    cPosition,
    tPosition,
    isCancellingAll, // 导出全撤操作锁状态
    isValidating, // 导出订单验证状态

    // 方法
    isSelected,
    handleOrderClick,
    placeOrder,
    cancelOrder,
    clearSelection,
    getTotalVolume,
    addActiveOrder,
    removeActiveOrder,
    clearActiveOrders,
    cancelAllOrders,
    cancelAllAccountOrders,
    incrementCancelCount,
    incrementTradeCount
  }
}
